<?php
header('Content-Type: application/json; charset=utf-8');

// 数据库连接信息
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "search_question_db";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die(json_encode([
        "code" => 0,
        "data" => [
            "message" => "数据库连接失败"
        ],
        "message" => "上传失败"
    ]));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['json_file']) || $_FILES['json_file']['error'] !== UPLOAD_ERR_OK) {
        die(json_encode([
            "code" => 0,
            "data" => [
                "message" => "文件上传失败"
            ],
            "message" => "上传失败"
        ]));
    }

    $jsonFile = $_FILES['json_file']['tmp_name'];
    $jsonContent = file_get_contents($jsonFile);

    if ($jsonContent === false) {
        die(json_encode([
            "code" => 0,
            "data" => [
                "message" => "读取文件失败"
            ],
            "message" => "上传失败"
        ]));
    }

    $questions = json_decode($jsonContent, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        die(json_encode([
            "code" => 0,
            "data" => [
                "message" => "JSON格式错误"
            ],
            "message" => "上传失败"
        ]));
    }

    $successCount = 0;
    $errorCount = 0;

    foreach ($questions as $questionData) {
        if (isset($questionData['question']) && isset($questionData['answer'])) {
            $question = $conn->real_escape_string($questionData['question']);
            $answer = $conn->real_escape_string($questionData['answer']);

            $sql = "INSERT INTO questions (question, answer) VALUES ('$question', '$answer')";

            if ($conn->query($sql) === TRUE) {
                $successCount++;
            } else {
                $errorCount++;
            }
        } else {
            $errorCount++;
        }
    }

    $conn->close();

    echo json_encode([
        "code" => 1,
        "data" => [
            "success" => $successCount,
            "errors" => $errorCount,
            "message" => "题库上传成功"
        ],
        "message" => "上传成功"
    ]);
} else {
    die(json_encode([
        "code" => 0,
        "data" => [
            "message" => "无效的请求方法"
        ],
        "message" => "上传失败"
    ]));
}
?>